package com.xxl.job.admin.custom;

import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.core.biz.model.JobInfoParam;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.dao.XxlJobLogDao;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务管理业务实现
 */
@Service
public class JobManagementBizImpl implements JobManagementBiz {

    @Resource
    private XxlJobInfoDao xxlJobInfoDao;

    @Resource
    private XxlJobLogDao xxlJobLogDao;

    @Resource
    private XxlJobGroupDao xxlJobGroupDao;

    @Override
    public ReturnT<String> addJob(JobInfoParam jobInfoParam) {
        try {
            setJobGroupId(jobInfoParam);
            XxlJobInfo jobInfo = convertToXxlJobInfo(jobInfoParam);
            int result = xxlJobInfoDao.save(jobInfo);
            return result > 0 ? new ReturnT<String>(String.valueOf(jobInfo.getId())): ReturnT.FAIL;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "添加任务失败: " + e.getMessage());
        }
    }

    @Override
    public ReturnT<String> updateJob(JobInfoParam jobInfoParam) {
        try {
            if (jobInfoParam.getId() == null) {
                return new ReturnT<>(ReturnT.FAIL_CODE, "任务ID不能为空");
            }

            XxlJobInfo existJob = xxlJobInfoDao.loadById(jobInfoParam.getId());
            if (existJob == null) {
                return new ReturnT<>(ReturnT.FAIL_CODE, "任务不存在");
            }
            setJobGroupId(jobInfoParam);
            XxlJobInfo jobInfo = convertToXxlJobInfo(jobInfoParam);
            jobInfo.setId(jobInfoParam.getId());
            int result = xxlJobInfoDao.update(jobInfo);
            return result > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "更新任务失败: " + e.getMessage());
        }
    }

    private void setJobGroupId(JobInfoParam jobInfoParam) throws Exception {
        if(null == jobInfoParam.getAppName() || jobInfoParam.getAppName().isEmpty()) {
            throw new Exception("需要选择执行器");
        }
        String appName = jobInfoParam.getAppName();
        List<XxlJobGroup> groups = xxlJobGroupDao.pageList(0,1, appName, null);
        if(null == groups || groups.size() == 0) {
            throw new Exception("执行器不存在");
        }
        XxlJobGroup group = groups.get(0);
        jobInfoParam.setJobGroup(group.getId());
    }

    @Override
    public ReturnT<String> startJob(int jobId) {
        try {
            XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
            if (jobInfo == null) {
                return new ReturnT<>(ReturnT.FAIL_CODE, "任务不存在");
            }

            jobInfo.setTriggerStatus(1); // 1表示启用
            int result = xxlJobInfoDao.update(jobInfo);
            return result > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "启动任务失败: " + e.getMessage());
        }
    }

    @Override
    public ReturnT<String> pauseJob(int jobId) {
        try {
            XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
            if (jobInfo == null) {
                return new ReturnT<>(ReturnT.FAIL_CODE, "任务不存在");
            }

            jobInfo.setTriggerStatus(0); // 0表示停止
            int result = xxlJobInfoDao.update(jobInfo);
            return result > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "暂停任务失败: " + e.getMessage());
        }
    }

    @Override
    public ReturnT<String> removeJob(int jobId) {
        try {
            // 先删除任务日志
            xxlJobLogDao.delete(jobId);
            // 再删除任务
            int result = xxlJobInfoDao.delete(jobId);
            return result > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "删除任务失败: " + e.getMessage());
        }
    }

    /**
     * 将参数DTO转换为实体对象
     */
    private XxlJobInfo convertToXxlJobInfo(JobInfoParam param) {
        XxlJobInfo jobInfo = new XxlJobInfo();
        jobInfo.setJobGroup(param.getJobGroup());
        jobInfo.setJobDesc(param.getJobDesc());
        jobInfo.setAuthor(param.getAuthor());
        jobInfo.setScheduleType(param.getScheduleType());
        jobInfo.setScheduleConf(param.getScheduleConf());
        jobInfo.setGlueType(param.getGlueType());
        jobInfo.setExecutorHandler(param.getExecutorHandler());
        jobInfo.setExecutorParam(param.getExecutorParam());
        jobInfo.setExecutorRouteStrategy(param.getExecutorRouteStrategy());
        jobInfo.setMisfireStrategy(param.getMisfireStrategy());
        jobInfo.setExecutorBlockStrategy(param.getExecutorBlockStrategy());
        jobInfo.setTriggerStatus(param.getTriggerStatus());
        jobInfo.setAddTime(new java.util.Date());
        jobInfo.setUpdateTime(new java.util.Date());
        jobInfo.setGlueUpdatetime(new java.util.Date());
        return jobInfo;
    }
}
